package com.fcy.teamwork.business.chat

import android.annotation.SuppressLint
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import cn.jpush.im.android.api.content.CustomContent
import cn.jpush.im.android.api.content.TextContent
import cn.jpush.im.android.api.enums.ContentType
import cn.jpush.im.android.api.model.Message
import com.bumptech.glide.Glide
import com.fcy.teamwork.App
import com.fcy.teamwork.R
import com.fcy.teamwork.business.main.homepage.adapter.refresh
import com.fcy.teamwork.business.main.homepage.viewmodel.TaskMarketService
import com.fcy.teamwork.databinding.ItemChatMsgMeBinding
import com.fcy.teamwork.databinding.ItemChatMsgOtherBinding
import com.fcy.teamwork.databinding.ItemTaskBriefBinding
import com.fcy.teamwork.pojo.Job
import com.fcy.teamwork.repo.RetrofitClient
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

typealias ItemListener = (Message) -> Any?

class ChatMsgListAdapter : RecyclerView.Adapter<ChatMsgListAdapter.VH>() {
    private var source: ArrayList<Message> = arrayListOf()

    var onClickAction: ItemListener = {}

    @SuppressLint("NotifyDataSetChanged")
    fun submitData(newData: List<Message>): Int {
        source = ArrayList(newData)
        notifyDataSetChanged()
        return source.size - 1
    }

    class VH(private val binding: ViewBinding, private val action: ItemListener? = null) :
        RecyclerView.ViewHolder(binding.root) {
        fun initData(msg: Message) {
            when (binding) {
                is ItemChatMsgMeBinding -> {
                    binding.initMe(msg)
                }
                is ItemChatMsgOtherBinding -> {
                    binding.initOther(msg)
                }
                is ItemTaskBriefBinding -> {
                    CoroutineScope(Dispatchers.IO).launch {
                        val res = RetrofitClient.getService<TaskMarketService>()
                            .loadJobs(
                                1,
                                1,
                                job = Job().apply {
                                    id = (msg.content as CustomContent).getStringValue("jobId")
                                        .toInt()
                                }
                            )
                        launch(Dispatchers.Main) {
                            binding.refresh(res.data[0])
                        }
                    }
                }
            }
        }

        private fun ItemChatMsgMeBinding.initMe(msg: Message) {
            Glide.with(root)
                .load(
                    R.drawable.por1
                )
                .into(pvPortraitMe)
            action?.apply {
                pvPortraitMe.setOnClickListener {
                    this(msg)
                }
            }

            tvMineMsg.text = (msg.content as? TextContent)?.text
        }

        private fun ItemChatMsgOtherBinding.initOther(msg: Message) {
            Glide.with(root)
                .load(R.drawable.por2)
                .into(pvPortraitOther)
            tvMineMsg.text = (msg.content as? TextContent)?.text
            tvNikeName.text = msg.fromUser.nickname
            action?.apply {
                pvPortraitOther.setOnClickListener {
                    this(msg)
                }
            }
        }
    }

    override fun getItemViewType(position: Int) =
        if (source[position].contentType == ContentType.custom)
            2
        else if (TextUtils.equals(source[position].fromUser.userName, App.person.personId)) 0
        else 1


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
        val binding = when (viewType) {
            0 -> {
                ItemChatMsgMeBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
            }
            1 -> {
                ItemChatMsgOtherBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
            }
            2 -> {
                ItemTaskBriefBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
            }
            else -> {
                throw IllegalStateException("未知的item类型")
            }
        }
        return VH(binding, onClickAction)
    }

    override fun onBindViewHolder(holder: VH, position: Int) {
        holder.initData(source[position])
    }

    override fun getItemCount(): Int = source.size

    /**
     *
     * @return Int 最新的position坐标
     */
    fun addMsg(msg: Message): Int {
        source.add(msg)
        val position = source.size - 1
        notifyItemInserted(position)
        return position
    }
}